package yxy.game.pm2.module.godwar;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;

public class GodWarModule extends PlayerModule {

	private DateTime coolDownTime;// 冷却时间

	public DateTime getCoolDownTime() {
		return coolDownTime;
	}

	public void setCoolDownTime(DateTime coolDownTime) {
		this.coolDownTime = coolDownTime;
	}

	// func===========================================================================

	public boolean cooldown() {
		if (getCoolDownTime() == null) {
			return false;
		}
		return DateTime.now().isBefore(getCoolDownTime());
	}

	// redis==========================================================================

	static public String key(String playerCode) {
		return String.format("PLAYER:%s:MODULE:GODWAR", playerCode);
	}

	public void set() {
		try {
			setv(key(getPlayerCode()), this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	static public GodWarModule get(String playerCode) {
		try {
			GodWarModule module = getv(key(playerCode));
			if (module == null) {
				module = MySQLCacheDAO.getV(key(playerCode), GodWarModule.class);
				if(module != null){module.set();}//把数据同步到redis
			}

			if (module == null) {
				module = create(playerCode);
			}
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	static private GodWarModule create(String playerCode) {
		GodWarModule module = new GodWarModule();
		module.setPlayerCode(playerCode);
		module.set();
		return module;
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				GodWarModule godWarModule = getv(key(playerCode));
				if(godWarModule != null) MySQLCacheDAO.setV(key, godWarModule);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}

}
